package com.jimikongjian.service;

import com.jimikongjian.models.Token;
import com.jimikongjian.service.base.ITokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Created by fuxiuyang on 17-5-8.
 *
 * 对生成的token存入Redis
 */
@Service("tokenService")
public class TokenService implements ITokenService {

    @Autowired
    @Qualifier("redisService")
    private RedisService redisService;

    /**
     * token有效时长
     */
    @Value("${token.expireTime}")
    private Long tokenExpireTime;


    /**
     * 创建一个token关联上指定用户
     *
     * @param email 指定用户的邮箱
     * @return 生成的token
     */
    @Override
    public Token createToken(String email) {
        String tokenString = UUID.randomUUID().toString().replace("-","");

        Token token = new Token();

        token.setEmail(email);
        token.setToken(tokenString);

        if (redisService.set(email, token, tokenExpireTime)){
            return token;
        }
        return null;
    }

    /**
     * 检查token是否有效
     *
     * @param token
     * @return 是否有效
     */
    @Override
    public boolean checkToken(Token token) {
        if (token == null || token.getEmail() == null) return false;
        Token temp = (Token) redisService.get(token.getEmail());
        if (temp == null) return false;

        String tokenString = temp.getToken();

        if (token.getToken().equals(tokenString)){
            redisService.set(token.getEmail(), token, tokenExpireTime);
            return true;
        }

        return false;
    }

    /**
     * 从字符串中解析token
     *
     * @param authentication 加密后的字符串
     * @return
     */
    @Override
    public Token getToken(String authentication) {
        return null;
    }

    /**
     * 清除token
     *
     * @param email 登录用户的邮箱
     */
    @Override
    public void deleteToken(String email) {
        redisService.remove(email);
    }
}
